<?php

namespace app\common\model;

use app\common\exception\BusinessException;
use app\common\service\UserService;

class OrderBonusSettlement extends Base
{
    /**
     * 开启自动时间戳
     * @var bool
     */
    protected $autoWriteTimestamp = false;

    public array $status_map = [
        '1' => '处理中',
        '2' => '已结算',
        '3' => '结算失败',
    ];

    /**
     * createOrder
     * @param $agent_id
     * @return void
     * @throws
     */
    public function createOrder($agent_id)
    {
        // 01.检查财务信息是否完整
        $agentInfo = app(UserService::class)->getUserById($agent_id);
        if (empty($agentInfo['realname']) || empty($agentInfo['alipay_account'])) {
            return;
        }

        // 02.检查总金额是否达标，满足结算标准
        $orderBonusItemModel = new OrderBonusItem();
        $threeDaysAgoTime = strtotime(date('Y-m-d', strtotime('-7 days')));
        $where = [
            ['agent_id', '=', $agent_id],
            ['is_settlement', '=', 0],
            ['is_build_settlement_order', '=', 0],
            ['status', '=', 1],
            ['create_time', '<=', $threeDaysAgoTime],
        ];
        $bonus_amount = $orderBonusItemModel->where($where)->sum('bonus_amount');
        if ($bonus_amount < 10) {
            return;
        }

        // 03.提取全部分红明细
        $allOrderBonusItem = $orderBonusItemModel->where($where)->select()->toArray();
        if (!$allOrderBonusItem) {
            return;
        }

        // 04.生成主单(结算单)
        $time = time();
        $saveMainData = [
            'order_sn' => createOrderNo('J'),
            'order_amount' => $bonus_amount,
            'real_amount' => $bonus_amount,
            'agent_id' => $agent_id,
            'settlement_username' => $agentInfo['realname'],
            'settlement_account' => $agentInfo['alipay_account'],
            'create_time' => $time,
            'update_time' => $time,
        ];
        $mainOrderId = $this->add_data($saveMainData);
        if (!$mainOrderId) {
            throw new BusinessException('生成结算单失败');
        }

        // 05.循环生成子单(结算单明细)
        $orderBonusSettlementItem = new OrderBonusSettlementItem();
        foreach ($allOrderBonusItem as $orderBonusItem) {
            $saveSubData = [
                'order_id' => $mainOrderId,
                'bonus_item_id' => $orderBonusItem['id'],
                'create_time' => $time,
                'update_time' => $time,
            ];
            $isAdd = $orderBonusSettlementItem->add_data($saveSubData);
            if (!$isAdd) {
                throw new BusinessException('保存结算单明细失败');
            }
        }

        // 06.标记所有的分红明细已经生成结算单
        $allOrderBonusItemId = array_column($allOrderBonusItem, 'id');
        $where = [['id', 'in', $allOrderBonusItemId]];
        $tagData = [
            'is_build_settlement_order' => 1
        ];
        $isUpdate = $orderBonusItemModel->save_data($tagData, $where);
        if (!$isUpdate) {
            throw new BusinessException('标记所有的分红明细已经生成结算单失败');
        }
    }
}